package cc.momas;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.LinkedHashMap;

/**
 * @author Sod-Momas
 * @since 2021-04-16
 */
public class ExportListener extends AnalysisEventListener<LinkedHashMap<Integer, Object>> {
    // txt输出目录
    public static final Path outputPath = Paths.get("./txt");
    // 记录当前行
    private int counter;

    public ExportListener() {
        // 如果没有这个目录，就创建这个目录
        if (Files.notExists(outputPath)) {
            try {
                Files.createDirectories(outputPath);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void invoke(LinkedHashMap lmap, AnalysisContext analysisContext) {
        final Object txt = lmap.get(0);
        try {
            Path filename = outputPath.resolve(++counter + ".txt");
            Files.writeString(filename, String.valueOf(txt));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
